#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from QRServer.utility import handle_uploaded_file, phone_json
from xls import xls_update
from models import*
import time



def search(POST):
    result_info = {'result':[],'message':None}
    result = Device.objects.filter(
        name__contains=POST['name'],
        num__contains=POST['num'],
        location__contains=POST['location'],
        date_of_purchase__contains=POST['selYear'],
        man__contains=POST['man']
    )

    for device in result:
        result_info['result'].append([
            device.num,
            device.name,
            device.type.pattern,
            device.type.standard,
            device.unit,
            device.location,
            device.man,
            device.status,
        ])

    length = len(result_info['result'])
    if length <= 10 and length:
        result_info['message'] = '搜索完成！共计'+str(length)+'个设备。'
    elif length:
        result_info['message'] = '搜索完成！共计'+str(length)+'个设备。建议通过增加搜索项来缩小结果范围。'
    else:
        result_info['message'] = '(T_T) 一个设备都没找到,扩大一下范围呗？'
    return result_info


@csrf_exempt
def phone(request):
    if request.method=="POST":
        try:
            GETinfo = {'num': request.POST['num']}
        except:
            raise Http404
        theDevice = get_object_or_404(Device, num=request.POST['num'])
        if request.POST['flag'] == '0':
            QRinfo = theDevice.phone()
            return HttpResponse(phone_json(QRinfo, GETinfo))
        elif request.POST['flag'] == '1':
            QRinfo = theDevice.type.phone()
            return HttpResponse(phone_json(QRinfo, GETinfo))
    raise Http404


@csrf_exempt
def QRcode(request):
    if request.method=="POST":
        try:
            theDevice = Device.objects.get(num=request.POST['num'])
            print "Test1 num = ", request.POST['num']
        except Device.DoesNotExist:
            error_message = "查找错误：设备不存在。"
            return render_to_response('devices/QRCode.html', locals(), context_instance=RequestContext(request))
        print "Test2 try to find device."
        uncode = theDevice.unqrcode()
        print "Test3 found!"
    return render_to_response('devices/QRCode.html', locals(), context_instance=RequestContext(request))


@login_required
@csrf_exempt
def xls_upload(request):
    error = True
    message = None
    if request.method=="POST":
        if request.FILES.has_key('xls'):
            '''TODO 经测试此处无法判断文件类型'''
            handle_uploaded_file(request.FILES['xls'], 'temp.xls')
            message, error = xls_update('/tmp/temp.xls')
            if not error:
                new_type, new_device = message[0], message[1]
        else:
            error = True
            message = "请先选择要上传的文件（xls版本只支持2003）"
    return render_to_response('devices/xlsupload.html', locals(), context_instance=RequestContext(request))


@csrf_exempt
def devices_search(request):
    message = "表格至少填写一项，支持模糊查询。(时间查询暂时只能精确到年。)"
    result = []
    '''TODO 此处应该从数据获取范围'''
    year = range(2000, time.localtime(time.time()).tm_year)
    month = range(1, 13)

    if request.method=="POST":
        result_info = search(request.POST)
        '''result 的格式是两层列表，第一层是设备，第二层是设备信息'''
        result = result_info['result']
        message = result_info['message']
    return render_to_response('devices/search.html', locals(), context_instance=RequestContext(request))


@login_required
@csrf_exempt
def admin_QRroom(request, building, room):
    place = building.encode('utf-8') + '#教学楼' + room.encode('utf-8')
    devices = Device.objects.filter(location=place)
    return render_to_response('devices/deviceRoom.html', locals(), context_instance=RequestContext(request))


@login_required
@csrf_exempt
def admin_QRbuilding(request, building):
    place = building.encode('utf-8') + '#教学楼'
    devices = Device.objects.filter(location=place)
    return render_to_response('devices/deviceRoom.html', locals(), context_instance=RequestContext(request))
